﻿
package {
	import flash.events.KeyboardEvent;
	
	public class Controls {
		private var _upKey:uint;
		private var _downKey:uint;
		private var _leftKey:uint;
		private var _rightKey:uint;
		private var _bird:Bird;
		private var _horizontalDown:Boolean = false;
		private var _verticalDown:Boolean = false;
		
		public function Controls(
			upKey:uint,
			downKey:uint,
			leftKey:uint, 
			rightKey:uint,
			bird:Bird = null
		) {
			_upKey = upKey;
			_downKey = downKey;
			_leftKey = leftKey;
			_rightKey = rightKey;
			_bird = bird;
			_bird.sprite.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler);
			_bird.sprite.stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
		}
		
		public function get bird():Bird {
			return _bird;
		}
		
		public function set bird(bird:Bird):void {
			_bird = bird;
		}
		
		public function keyboardHandler(event:KeyboardEvent):void {
			handleKeypress(event.charCode != 0 ? event.charCode : event.keyCode);
		}
		
		public function keyUpHandler(event:KeyboardEvent):void {
			if (event.charCode == _upKey || (event.charCode == 0 && event.keyCode == _upKey))
				_verticalDown = false;
		}
		
		public function handleKeypress(code:uint):void {
			switch (code) {
				case _upKey:
					if (!_verticalDown) {
						_bird.flap();
						_verticalDown = true;
					}
					break;
				case _downKey:
					// Do nothing
					break;
				case _leftKey:
					_horizontalDown = true;
					_bird.goLeft();
					break;
				case _rightKey:
					_horizontalDown = true;
					_bird.goRight();
					break;
			}			
		}
	}
}